﻿using System;
using System.Dynamic;
using System.Net.Sockets;
using System.Text;

namespace Infrastructure.Sockets.models
{
    /// <summary>
    /// 状态
    /// </summary>
    public class TcpClientState
    {
        /// <summary>
        /// 锁
        /// </summary>
        public object Lock { get; } = new object();

        /// <summary>
        /// 与客户端相关的TcpClient
        /// </summary>
        public TcpClient TcpClient { get; }

        /// <summary>
        /// 获取缓冲区
        /// </summary>
        public byte[] Buffer { get; private set; }

        /// <summary>
        /// 获得数据长度
        /// </summary>
        public int BufferLength { get; set; }

        /// <summary>
        /// 数据数组
        /// </summary>
        public byte[] BufferData
        {
            get
            {
                byte[] data = new byte[BufferLength];
                if (Buffer == null || BufferLength == 0)
                {
                    return data;
                }
                Array.Copy(Buffer, 0, data, 0, BufferLength);
                return data;
            }
        }

        /// <summary>
        /// 获取网络流
        /// </summary>
        public NetworkStream NetworkStream => TcpClient.GetStream();

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="buffer"></param>
        public TcpClientState(TcpClient tcpClient, byte[] buffer)
        {
            TcpClient = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient));
            Buffer = buffer ?? throw new ArgumentNullException(nameof(buffer));
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void Close()
        {
            //关闭数据的接受和发送
            TcpClient.Close();
            Buffer = null;
        }
    }
}
